/*global jQuery, $, google, strToLatLngObj */

/**
 * Retreives the min and max values for latitude and longitude of all markers
 * @param {Array} data
 * @return {Object} minLat, maxLat, minLng, maxLng
 */
var getMinMaxLatLng = null;
getMinMaxLatLng = function (data) {
    var i = 0, minLat = 0, maxLat = 0, minLng = 0, maxLng = 0, curLng = 0, curLat = 0, multiplicator = 1000000,
		latlng = '';
    
    for (i = 0; i < data.results.length; i++) {
        latlng = strToLatLngObj(data.results[i].place.point);
        curLng = latlng.lng * multiplicator;
        curLat = latlng.lat * multiplicator;
        
        if (0 === i) {
            minLat = maxLat = curLat;
            minLng = maxLng = curLng;
        }
        
        if (curLng > maxLng) {
            maxLng = curLng;
        }
        else if (curLng < minLng) {
			minLng = curLng;
        }
        
        if (curLat > maxLat) {
            maxLat = curLat;
        }
        else if (curLat < minLat) {
        	minLat = curLat;
        }
    }
    
    return {
        'minLat': minLat / multiplicator,
        'maxLat': maxLat / multiplicator,
        'minLng': minLng / multiplicator,
        'maxLng': maxLng / multiplicator
    };
    
};




function resultMap(data, mapSelector) {
    var useragent = null, mapdiv = null, centerLatLng = null, myOptions = null, map = null, marker = null, minMax = null, ne = null, sw = null,
		myLatLngBounds = null,
		latlng = null,
		i = 0;
    
    useragent = navigator.userAgent;
    
    mapdiv = $(mapSelector).get(0);
	
	var window_width = $(window).width();
    
    mapdiv.style.width = (window_width) + 'px';
    mapdiv.style.height = ((parseInt(window_width, 10) / 4) * 3) + 'px';
    
    // centerLatLng = new google.maps.LatLng(0, 0);
    minMax = getMinMaxLatLng(data);
    
    ne = new google.maps.LatLng(minMax.minLat, minMax.minLng);
    sw = new google.maps.LatLng(minMax.maxLat, minMax.maxLng);
    
    myLatLngBounds = new google.maps.LatLngBounds(ne, sw);
    centerLatLng = myLatLngBounds.getCenter();
    
    
    myOptions = {
        zoom: 15,
        center: centerLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false
    };
    
    map = new google.maps.Map(mapdiv, myOptions);
    
    for (i = 0; i < data.results.length; ++i) {
        latlng = strToLatLngObj(data.results[i].place.point);
        
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(latlng.lat, latlng.lng),
            map: map,
            title: data.results[i].place.title
        });
    }
	
    
    //User Position - green arrow
	
	if (rateme.MY_POS !== null) {
		var myLatLng = new google.maps.LatLng(rateme.MY_POS.lat, rateme.MY_POS.lng);
		marker = new google.maps.Marker({
	        position: myLatLng,
	        map: map,
	        title: 'MyPosition',
			icon: 'http://maps.google.com/mapfiles/arrow.png' 
	    });	
	}
    
   
    
    
    $(document).trigger('maploaded');
    
}

